"""Django生产环境设置配置

LinkBook项目的生产环境配置文件。
"""

from .base import *
from decouple import config
import os

# 调试模式（生产环境必须关闭）
DEBUG = False

# 允许的主机（从环境变量获取）
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='').split(',')

# 生产环境数据库配置
from .database import PRODUCTION_DATABASE_CONFIG, DatabaseRouter, QUERY_OPTIMIZATION

DATABASES = PRODUCTION_DATABASE_CONFIG

# 数据库路由
DATABASE_ROUTERS = ['linkbook.settings.database.DatabaseRouter']

# 查询优化配置
DEFAULT_PAGE_SIZE = QUERY_OPTIMIZATION['DEFAULT_PAGE_SIZE']
MAX_PAGE_SIZE = QUERY_OPTIMIZATION['MAX_PAGE_SIZE']

# CORS设置（生产环境严格控制）
CORS_ALLOWED_ORIGINS = config('CORS_ALLOWED_ORIGINS', default='').split(',')
CORS_ALLOW_CREDENTIALS = True

# 安全设置
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000  # 1年
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_REFERRER_POLICY = 'strict-origin-when-cross-origin'

# Cookie安全设置
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SAMESITE = 'Lax'

# 静态文件配置（生产环境）
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
WHITENOISE_USE_FINDERS = True
WHITENOISE_AUTOREFRESH = True

# 邮件配置（生产环境）
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT', default=587, cast=int)
EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool)
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL')

# 日志配置（生产环境）
LOGGING['handlers']['file']['filename'] = '/var/log/linkbook/django.log'
LOGGING['loggers']['linkbook']['level'] = 'INFO'
LOGGING['handlers']['console']['level'] = 'WARNING'

# 错误报告
ADMINS = [
    ('Admin', config('ADMIN_EMAIL', default='admin@linkbook.com')),
]
MANAGERS = ADMINS

# 服务器错误邮件
SERVER_EMAIL = config('SERVER_EMAIL', default='server@linkbook.com')

# 缓存配置（生产环境使用Redis）
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': config('REDIS_URL'),
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            'CONNECTION_POOL_KWARGS': {
                'max_connections': 50,
                'retry_on_timeout': True,
                'socket_keepalive': True,
                'socket_keepalive_options': {},
            },
            'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor',
            'SERIALIZER': 'django_redis.serializers.json.JSONSerializer',
        },
        'KEY_PREFIX': 'linkbook_prod',
        'TIMEOUT': 300,
        'VERSION': 1,
    },
    # 会话缓存
    'sessions': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': config('REDIS_URL'),
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            'CONNECTION_POOL_KWARGS': {
                'max_connections': 20,
                'retry_on_timeout': True,
            },
        },
        'KEY_PREFIX': 'linkbook_sessions',
        'TIMEOUT': 86400,  # 24小时
    },
}

# 会话配置（生产环境）
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 86400  # 24小时

# 文件上传限制（生产环境更严格）
FILE_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024  # 5MB
DATA_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024  # 5MB
FILE_UPLOAD_PERMISSIONS = 0o644

# 数据库连接池配置
DATABASES['default']['CONN_MAX_AGE'] = 600
DATABASES['default']['OPTIONS']['MAX_CONNS'] = 20

# 性能优化
USE_ETAGS = True
USE_THOUSAND_SEPARATOR = True

# 数据库连接池优化
DATABASES['default']['CONN_HEALTH_CHECKS'] = True
DATABASES['default']['OPTIONS']['MAX_CONNS'] = config('DB_MAX_CONNS', default=20, cast=int)

# 查询优化
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# 静态文件优化
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
WHITENOISE_USE_FINDERS = True
WHITENOISE_AUTOREFRESH = True
WHITENOISE_MAX_AGE = 31536000  # 1年

# Gzip压缩
WHITENOISE_SKIP_COMPRESS_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'zip', 'gz', 'tgz', 'bz2', 'tbz', 'xz', 'br']

# 模板缓存
TEMPLATES[0]['OPTIONS']['loaders'] = [
    ('django.template.loaders.cached.Loader', [
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    ]),
]

# 会话优化
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'sessions'
SESSION_COOKIE_AGE = 86400  # 24小时
SESSION_SAVE_EVERY_REQUEST = False
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

# API限流配置
REST_FRAMEWORK.update({
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/hour',
        'user': '1000/hour'
    }
})

# Sentry错误监控（如果配置了）
SENTRY_DSN = config('SENTRY_DSN', default='')
if SENTRY_DSN:
    import sentry_sdk
    from sentry_sdk.integrations.django import DjangoIntegration
    from sentry_sdk.integrations.celery import CeleryIntegration
    
    sentry_sdk.init(
        dsn=SENTRY_DSN,
        integrations=[
            DjangoIntegration(auto_enabling=True),
            CeleryIntegration(auto_enabling=True),
        ],
        traces_sample_rate=0.1,
        send_default_pii=True,
        environment='production',
    )